package com.example.java_gobang.game;

import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author krystal
 * @date 2023/3/12 18:59
 */
//这个类表示匹配器，通过这个类完成整个匹配功能
@Component
public class Matcher {
    //创建三个匹配队列
    private Queue<User> normalQueue=new LinkedList<>();
    private Queue<User> highQueue=new LinkedList<>();
    private Queue<User> veryHighQueue=new LinkedList<>();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private RoomManager roomManager;

    @Autowired
    private ObjectMapper objectMapper=new ObjectMapper();

    //操作匹配队列的方法
    //把玩家放入到匹配队列中
    public void add(User user){
        if (user.getScore()<2000){
            synchronized (normalQueue){
                normalQueue.offer(user);
                normalQueue.notify();
            }
            System.out.println("把玩家"+user.getUsername()+"加入到了normalQueue中！");
        }else if (user.getScore()>=2000 && user.getScore()<3000){
            synchronized (highQueue){
                highQueue.offer(user);
                highQueue.notify();
            }
            System.out.println("把玩家"+user.getUsername()+"加入到了highQueue中！");
        }else {
            synchronized (veryHighQueue){
                veryHighQueue.offer(user);
                veryHighQueue.notify();
            }
            System.out.println("把玩家"+user.getUsername()+"加入到了veryHighQueue中！");
        }
    }

    //当玩家点击停止匹配时，就需要把玩家从匹配队列中删除
    public void remove(User user){
        if (user.getScore()<2000){
            synchronized (normalQueue){
                normalQueue.remove(user);
            }
            System.out.println("把玩家"+user.getUsername()+"移除出了normalQueue中！");
        }else if (user.getScore()>=2000 && user.getScore()<3000){
            synchronized (highQueue){
                highQueue.remove(user);
            }
            System.out.println("把玩家"+user.getUsername()+"移除出了highQueue中！");
        }else {
            synchronized (veryHighQueue){
                veryHighQueue.remove(user);
            }
            System.out.println("把玩家"+user.getUsername()+"移除出了veryHighQueue中！");
        }
    }

    public Matcher(){
        //创建三个线程，分别针对三个匹配队列进行操作
        Thread t1=new Thread(){
            @Override
            public void run() {
                //扫描normalQueue
                while (true){
                    handlerMatch(normalQueue);
                }
            }
        };
        t1.start();

        Thread t2=new Thread(){
            @Override
            public void run() {
                //扫描highQueue
                while (true){
                    handlerMatch(highQueue);
                }
            }
        };
        t2.start();

        Thread t3=new Thread(){
            @Override
            public void run() {
                //扫描veryHighQueue
                while (true){
                    handlerMatch(veryHighQueue);
                }
            }
        };
        t3.start();
    }

    private void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue){
            try {
                //1、检测队列中元素个数是否达到2
                while (matchQueue.size()<2){
                    matchQueue.wait();
                }
                //2、尝试从队列中取出两个玩家
                User player1= matchQueue.poll();
                User player2= matchQueue.poll();
                System.out.println("匹配出两个玩家："+player1.getUsername()+","+player2.getUsername());
                //3、获取到玩家的websocket的会话
                WebSocketSession session1=onlineUserManager.getFromGameHall(player1.getUserId());
                WebSocketSession session2=onlineUserManager.getFromGameHall(player2.getUserId());
                if (session1==null){
                    //如果玩家1不在线了，就把玩家2重新放回到匹配队列中
                    matchQueue.offer(player2);
                    return;
                }
                if (session2==null){
                    matchQueue.offer(player1);
                    return;
                }
                if (session1==session2){
                    matchQueue.offer(player1);
                    return;
                }
                //4、把这两个玩家放到同一个房间
                Room room=new Room();
                roomManager.add(room, player1.getUserId(), player2.getUserId());
                //5、给玩家反馈匹配成功的信息
                MatchResponse response1=new MatchResponse();
                response1.setOk(true);
                response1.setMessage("matchSuccess");
                String json1=objectMapper.writeValueAsString(response1);
                session1.sendMessage(new TextMessage(json1));
                MatchResponse response2=new MatchResponse();
                response2.setOk(true);
                response2.setMessage("matchSuccess");
                String json2=objectMapper.writeValueAsString(response2);
                session2.sendMessage(new TextMessage(json2));
            }catch (InterruptedException | IOException e){
                e.printStackTrace();
            }
        }
    }
}
